package com.shiqi.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 *[
 *     {
 *         "resource":"/order/add",
 *         "controlBehavior": 0,
 *         "count": 10.0,
 *         "grade": 1,
 *         "limitApp": "default",
 *         "strategy": 0
 *     }
 * ]
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/add")
    @SentinelResource(value = "add", blockHandler = "addBlockHandler")
    public String add() {
        System.out.println("下单成功");
        return "success，下单成功，";
    }

    @GetMapping("/addThread")
    @SentinelResource(value = "addThread", blockHandler = "addBlockHandler")
    public String addThread() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        System.out.println("下单成功");
        return "success，下单成功，";
    }

    @GetMapping("/addId/{id}")
    @SentinelResource(value = "addId", blockHandler = "addBlockHandlerId")
    public String addId(@PathVariable String id) {
        System.out.println("下单成功");
        return "success，下单成功，";
    }

    public String addBlockHandlerId(String id, BlockException e) {
        System.out.println(id);
        e.printStackTrace();
        return "流控";
    }

    public String addBlockHandler(BlockException e) {
        e.printStackTrace();
        return "流控";
    }
}
